package cn.com.header.core.support.web.springmvc;

import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author liangzhongqiu789@sina.com
 * @date 2017-05-23
 * @time 09:29
 */
public abstract class FileDownloadBaseController extends BaseController {

    protected ResponseEntity<byte[]> writeToResponseForDownload(InputStream in, String fileName) throws IOException {
        byte[] bytes = ByteStreams.toByteArray(in);
        Closeables.close(in, true);
        return writeToResponseForDownload(bytes, fileName);
    }

    protected ResponseEntity<byte[]> writeToResponseForDownload(File file) throws IOException {
        return writeToResponseForDownload(Files.toByteArray(file), file.getName());
    }

    protected ResponseEntity<byte[]> writeToResponseForDownload(byte[] bytes, String fileName) {
        Objects.requireNonNull(bytes, "响应字节不能为空！！！");
        Objects.requireNonNull(fileName, "文件名不能为空！！！");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", new String(fileName.getBytes(StandardCharsets.UTF_8)), StandardCharsets.ISO_8859_1);
        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.CREATED);
    }

}
